<template>
  <div>
    <input v-model="prompt" placeholder="请输入问题..." />
    <button @click="startStream">发送</button>

    <p v-if="loading">生成中...</p>
    <pre>{{ result }}</pre>
  </div>
</template>

<script>
export default {
  data() {
    return {
      result: '',
      loading: false,
      prompt: '',
    };
  },
  methods: {
    startStream() {
      this.result = '';
      this.loading = true;

      const source = new EventSource(`http://localhost:2626/api/deepseek/stream?prompt=${encodeURIComponent(this.prompt)}`);

      source.onmessage = (event) => {
        if (event.data === '[DONE]') {
          console.log('接收完成');
          source.close();
          this.loading = false;
        } else {
          this.result += event.data;
        }
      };

      source.onerror = (error) => {
        console.error('流式连接出错（可能是正常断开）', error);
        source.close();
        this.loading = false;
      };

      source.onopen = () => {
        console.log('连接已开启');
      };
    }
  }
}
</script>
